﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SMSSendTest
{
    public class SmsService
    {
        private readonly string apiUrl = "https://api.example.com/send-sms";
        private readonly string apiKey = "你的API密钥";

        public async Task<string> SendSmsAsync(string phoneNumber, string message)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var requestBody = new
                    {
                        apiKey = this.apiKey,
                        phoneNumber = phoneNumber,
                        message = message
                    };

                    string jsonBody = JsonConvert.SerializeObject(requestBody);
                    StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        return result; // 这里返回的可能是发送成功的消息或者短信ID等  
                    }
                    else
                    {
                        // 处理错误，例如返回错误信息  
                        string errorMessage = await response.Content.ReadAsStringAsync();
                        throw new Exception($"发送短信失败: {errorMessage}");
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获并处理异常  
                Console.WriteLine($"发送短信时发生错误: {ex.Message}");
                return null;
            }
        }
    }
}
